﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

// Additional Libraries
using LocalDatabase.Model;
using LocalDatabase.ViewModel;
using System.IO.IsolatedStorage;
using Microsoft.Phone.Notification;
using Microsoft.Phone.Shell;
using System.Security.Cryptography;
using System.Text;
using Microsoft.Phone.Net.NetworkInformation;

namespace findMePanorama
{
    public partial class Login : PhoneApplicationPage
    {
        IsolatedStorageSettings settings;
        Microsoft.Phone.UserData.Contact phoneContact;
        FindMeFriendServiceReference.FindMeFriendServiceClient serviceClient;
      
           ProgressIndicator progress;
          


        // Constructor
        public Login()
        {
            InitializeComponent();
            settings = IsolatedStorageSettings.ApplicationSettings;
            serviceClient = new FindMeFriendServiceReference.FindMeFriendServiceClient();
            serviceClient.LogInCompleted += new EventHandler<FindMeFriendServiceReference.LogInCompletedEventArgs>(serviceClient_LogInCompleted);

            if (settings.Contains("Username"))
            {
                string username = settings["Username"].ToString();
                txtUsername.Text = username;
            }

            //<-- Progress bar and clock colors -->
            SystemTray.SetIsVisible(this, true);
            SystemTray.SetOpacity(this, 0.0);
            SystemTray.SetBackgroundColor(this, Colors.Black);
            SystemTray.SetForegroundColor(this, Colors.Green);
            progress = new ProgressIndicator();
            progress.IsIndeterminate = true;
            progress.Text = "Loading";
            SystemTray.SetProgressIndicator(this, progress);

            //<-- End progress bar and clock colors -->


            if (!DeviceNetworkInformation.IsNetworkAvailable && !DeviceNetworkInformation.IsWiFiEnabled)
            {
                MessageBox.Show("No Cellular or Wi-Fi network is available! Please verify your network connectivity.", "Network Error", MessageBoxButton.OK);
                while (NavigationService.RemoveBackEntry() != null) ;
            }
        }

        // Back OVERRIDE
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            //Sencillo este while elimina todos las posibles backs!!! Luego hace el comando de back tirandote al OS. 
            while (NavigationService.RemoveBackEntry() != null) ;
        }

        void serviceClient_LogInCompleted(object sender, FindMeFriendServiceReference.LogInCompletedEventArgs e)
        {
            Guid sessionToken = e.Result;
            if (sessionToken != new Guid())
            {
                if (settings.Contains("SessionToken"))      // Saving Session Token in Isolated Storage
                {
                    settings["SessionToken"] = sessionToken;
                }
                else
                {
                    settings.Add("SessionToken", sessionToken);
                }

                // Specify the local database connection string.
                string DBConnectionString = "Data Source=isostore:/FindMeFriends.sdf";

                // Create the database if it does not exist.
                using (FindMeDataContext db = new FindMeDataContext(DBConnectionString))
                {
                    if (!db.DatabaseExists())
                    {
                        // Create the local database.
                        db.CreateDatabase();

                        // Save changes to the database.
                        db.SubmitChanges();

                        Microsoft.Phone.UserData.Contacts phoneContacts = new Microsoft.Phone.UserData.Contacts();
                        phoneContacts.SearchCompleted += new EventHandler<Microsoft.Phone.UserData.ContactsSearchEventArgs>(phoneContacts_SearchCompleted);
                        phoneContacts.SearchAsync("", Microsoft.Phone.UserData.FilterKind.None, "FindMe Contact Search");

                        if (!settings.Contains("Username"))
                        {
                            settings.Add("Username", txtUsername.Text);
                        }
                        else
                        {
                            settings["Username"] = txtUsername.Text;
                        }
                    }
                    else
                    {
                        if (settings.Contains("Username"))
                        {
                            string lastUserName = settings["Username"].ToString();
                            if (lastUserName != txtUsername.Text)
                            {
                                db.FindMeFriends.DeleteAllOnSubmit(db.FindMeFriends);
                                db.SubmitChanges();
                                settings["Username"] = txtUsername.Text;
                            }
                        }
                    }
                }


                // Create the ViewModel object.
                App.FindMeFriendsViewModel = new FindMeViewModel(DBConnectionString);

                // Query the local database and load observable collections.
                App.FindMeFriendsViewModel.LoadFriendsFromDatabase();

                string channelName = txtUsername.Text + "Channel";
                App.pushChannel = HttpNotificationChannel.Find(channelName);

                if (App.pushChannel == null)
                {
                    if (settings.Contains("PushChannel"))
                    {
                        string lastChannel = settings["PushChannel"].ToString();
                        HttpNotificationChannel pushChannel = HttpNotificationChannel.Find(lastChannel);
                        if (pushChannel != null) { pushChannel.Close(); }
                    }

                    App.pushChannel = new HttpNotificationChannel(channelName);
                    App.pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(App.pushChannel_ChannelUriUpdated);
                    App.pushChannel.Open();
                    App.pushChannel.BindToShellToast();
                }
                else
                {
                    serviceClient.UpdatePushURIAsync(txtUsername.Text, sessionToken, App.pushChannel.ChannelUri.ToString());
                    App.pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(App.pushChannel_ChannelUriUpdated);
                }

                if (!settings.Contains("PushChannel"))
                {
                    settings.Add("PushChannel", channelName);
                }
                else
                {
                    settings["PushChannel"] = channelName;
                }

                settings.Save();
               progress.IsVisible = false;
                NavigationService.Navigate(new Uri("/panorama.xaml", UriKind.Relative));
            }
            else
            {
               progress.IsVisible = false;
                MessageBox.Show("LogIn failed! Please check your username and/or password and try again");
                txbForgotPassword.Visibility = System.Windows.Visibility.Visible;
            }
        }

        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
           progress.IsVisible = true;

            string validUsername = validateUsername();
            string validPassword = validatePassword();

            if (validUsername == "valid" && validPassword == "valid")
            {
                SHA1 sha1 = new SHA1Managed();
                byte[] passwordBytes = Encoding.Unicode.GetBytes(pswPassword.Password);
                byte[] hash = sha1.ComputeHash(passwordBytes);
                string hashedPassword = Encoding.Unicode.GetString(hash, 0, hash.Length);

                try
                {
                    serviceClient.LogInAsync(txtUsername.Text, hashedPassword);
                }
                catch (Exception) { }
            }
            else
            {
               progress.IsVisible = false;
                MessageBox.Show("Username and Password can't be emtpy");
            }
        }

        void phoneContacts_SearchCompleted(object sender, Microsoft.Phone.UserData.ContactsSearchEventArgs e)
        {
            try
            {
                var contacts = e.Results;
                if (contacts == null) return;

                foreach (Microsoft.Phone.UserData.Contact c in contacts)
                {
                    phoneContact = c;
                    var accounts = c.Accounts;
                    foreach (Microsoft.Phone.UserData.Account a in accounts)
                    {
                        if (a.Kind == Microsoft.Phone.UserData.StorageKind.Facebook)
                        {
                            string phoneNumber = (c.PhoneNumbers).FirstOrDefault() == null ? "NONE" : (c.PhoneNumbers).FirstOrDefault().PhoneNumber;
                            
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnRegister_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/RegisterPage.xaml", UriKind.Relative));
        }

        string validateUsername()
        {
            string username = txtUsername.Text;

            if (username == string.Empty)
            {
                return "*Username can't be empty";
            }

            return "valid";
        }

        string validatePassword()
        {
            string password = pswPassword.Password;

            if (password == string.Empty)
            {
                return "*Password can't be empty";
            }

            return "valid";
        }

        private void txbForgotPassword_Tap(object sender, GestureEventArgs e)
        {
            MessageBox.Show("Todavia no funciona gracias a que Ramon no ha hecho la pagina xaml para esto");
        }
    }
}